Grokking Python Fundamentals
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Course Overview
Python Basics
Python Overview
Python Application Areas
Your First Python Program
Python - Basic Syntax
Python Comments
Quiz
Python Variables and Operators
Python - Variables
Python - Data types
Python - Numbers
Python - Booleans
Python - Type Conversions
Python - Operators
Quiz
Python Conditionals
Introduction to Conditional Statements in Python
Python - If...Else
Python - Match Case
Quiz
Python loops
Introduction to loops in Python
Python - for loop
Python - while loop
Python - Loop Control
Python - for else and while else loop
Quiz
Introduction to Strings in Python
Python - String Operators
Python Slicing Strings
Python - String Methods
Quiz
Introduction to Array in Python
Python - Array Methods
Quiz
Introduction to Lists in Python
Python - Add and Remove List Items
Python - List Comprehension
Python - List Methods
Quiz
Introduction to Tuple in Python
Python - Unpack Tuple Items
Python - Join Tuples
Python - Tuple Methods
Quiz
Introduction to Dictionary in Python
Python - Nested Dictionaries
Python - Dictionary Methods
Quiz
Introduction to set in Python
Python - set Operations
Python - Set Methods
Quiz
Introductions to Function in Python
Python - Function Arguments
Recursive Functions
Python - Variable scope
Importing Modules
Quiz
Python - for loop

The for loop in Python is a versatile control structure that allows you to iterate over a sequence of elements, such as lists, tuples, strings, or any other iterable object. This type of loop is particularly useful for tasks that require the execution of a block of code for each element in a sequence.

In this lesson, we will explore the syntax, basic usage, and some advanced concepts associated with the for loop in Python.

Syntax of the for Loop

The basic syntax of a for loop in Python is as follows:

Image
Python3
. . . .

Explanation:

  • iterable: This is the collection of elements that the loop will iterate over. It can be a list, a tuple, a dictionary, a set, or any object that supports iteration.
  • variable: For each iteration of the loop, the variable takes on the value of the next element in the iterable.

Basic Example

Let’s look at a simple example to understand the basic functionality of the for loop.

Python3

. . . .

Explanation:

  • fruits = ['apple', 'banana', 'cherry']: Defines a list of fruits.
  • for fruit in fruits:: Starts a loop over the fruits list. With each iteration, the variable fruit will take the value of one item from the list.
  • print(fruit): Executes for each iteration of the loop, printing the current value of fruit.

This example demonstrates how to use a for loop to iterate over a list and perform an action with each element, which in this case is printing the element. This approach is clear and concise, avoiding the need for indexing and the associated risks of off-by-one errors or boundary issues.

Looping Through Dictionaries

Dictionaries in Python are key-value pairs. You can iterate over them in several ways, depending on whether you need access to keys, values, or both.

Example

Python3

. . . .

Explanation:

  • info = {'name': 'John', 'age': 30, 'city': 'New York'}: Initializes a dictionary with three key-value pairs.
  • for key in info:: Iterates over each key in the dictionary by default. If you need to iterate over values or key-value pairs, you could use info.values() or info.items(), respectively.
  • print(key, "->", info[key]): Prints each key and its corresponding value. To directly access both key and value in the loop, use for key, value in info.items():.

Nested Loops

A nested loop is a loop inside a loop. The "inner loop" will be executed one time for each iteration of the "outer loop".

Example

Python3

. . . .

Explanation:

  • matrix = [[1, 2, 3], [4, 5, 6]]: Sets up a list containing two lists, each with three integers.
  • for row in matrix:: The outer loop iterates over each sublist in matrix.
  • for num in row:: The inner loop iterates over each element in the current sublist referred to by row.
  • print(num, end=' '): Prints each number followed by a space instead of the default newline.
  • print(): After the inner loop completes for a sublist, it prints a newline to separate the rows visually.

Using the range() Function with Loops

The range() function in Python is frequently used with for loops to generate sequences of numbers. This function is extremely versatile and beneficial when you need to execute a loop a specific number of times. The range() function can be used in several ways depending on the parameters provided:

  1. Single parameter: Generates a sequence from 0 up to, but not including, the specified number.
  2. Two parameters: Generates a sequence from the first parameter to the second parameter, not including the second parameter.
  3. Three parameters: The third parameter specifies the step, or increment, between each number in the sequence.

Example

Python3

. . . .

Explanation:

  • for i in range(10):: Iterates over numbers 0 through 9. It uses range(10) which starts at 0 (default) and ends at 9 (one less than 10).
  • for i in range(1, 11):: Iterates from 1 to 10. It specifies the starting point of 1 and goes up to 10.
  • for i in range(1, 11, 2):: Iterates starting from 1 up to 10, incrementing by 2 each time, thus printing only odd numbers between 1 and 10.

The for loop in Python is an indispensable tool for iterating over sequences and performing repeated operations efficiently. By mastering this loop, along with utilities like the range() function, you can handle most common looping requirements with ease and clarity. Whether you're processing items in a list, executing tasks a specific number of times, or combining it with conditions and other control structures, the for loop enhances readability and reduces the chance for errors in your code.

Introduction to loops in Python
Python - while loop
Mark as Completed

On this page

Syntax of the for Loop

Basic Example

Looping Through Dictionaries

Example

Nested Loops

Example

Using the range() Function with Loops

Example